package com.ahdy.controller;

import com.ahdy.model.ChatRequest;
import com.ahdy.model.ChatResponse;
import com.ahdy.model.RoleContent;
import com.ahdy.service.SparkAiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/api/chat")
@CrossOrigin
public class Spark_AIController {

    @Autowired
    private SparkAiService sparkAiService;

    /**
     * 流式聊天接口 - 优化字符编码
     * 使用Server-Sent Events (SSE) 实现流式回复
     */
    @PostMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE + ";charset=UTF-8")
    public ResponseEntity<SseEmitter> chatStream(@RequestBody ChatRequest request) {
        log.info("收到流式聊天请求，消息长度: {} 字符",
                request.getMessage() != null ? request.getMessage().length() : 0);

        // 参数验证
        if (request.getMessage() == null || request.getMessage().trim().isEmpty()) {
            SseEmitter errorEmitter = new SseEmitter(1000L);
            try {
                ChatResponse errorResponse = new ChatResponse("错误：消息不能为空",
                        request.getSessionId(), true);
                errorEmitter.send(SseEmitter.event()
                        .name("error")
                        .data(errorResponse));
                errorEmitter.complete();
            } catch (Exception e) {
                errorEmitter.completeWithError(e);
            }

            return ResponseEntity.badRequest()
                    .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_EVENT_STREAM_VALUE + ";charset=UTF-8")
                    .header(HttpHeaders.CACHE_CONTROL, "no-cache")
                    .header(HttpHeaders.CONNECTION, "keep-alive")
                    .header("Access-Control-Allow-Origin", "*")
                    .header("Access-Control-Allow-Headers", "Content-Type")
                    .body(errorEmitter);
        }

        if (request.getMessage().length() > 4000) {
            SseEmitter errorEmitter = new SseEmitter(1000L);
            try {
                ChatResponse errorResponse = new ChatResponse("错误：消息长度不能超过4000字符",
                        request.getSessionId(), true);
                errorEmitter.send(SseEmitter.event()
                        .name("error")
                        .data(errorResponse));
                errorEmitter.complete();
            } catch (Exception e) {
                errorEmitter.completeWithError(e);
            }

            return ResponseEntity.badRequest()
                    .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_EVENT_STREAM_VALUE + ";charset=UTF-8")
                    .body(errorEmitter);
        }

        String sessionId = request.getSessionId();
        if (sessionId == null || sessionId.trim().isEmpty()) {
            sessionId = UUID.randomUUID().toString();
        }

        // 确保输入消息是UTF-8编码
        String utf8Message = ensureUtf8(request.getMessage().trim());
        String utf8SessionId = ensureUtf8(sessionId);

        try {
            SseEmitter emitter = sparkAiService.chatStream(utf8Message, utf8SessionId);

            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_EVENT_STREAM_VALUE + ";charset=UTF-8")
                    .header(HttpHeaders.CACHE_CONTROL, "no-cache")
                    .header(HttpHeaders.CONNECTION, "keep-alive")
                    .header("Access-Control-Allow-Origin", "*")
                    .header("Access-Control-Allow-Headers", "Content-Type")
                    .body(emitter);

        } catch (Exception e) {
            log.error("启动流式聊天失败: {}", e.getMessage());
            SseEmitter errorEmitter = new SseEmitter(1000L);
            try {
                ChatResponse errorResponse = new ChatResponse("错误：AI服务暂时不可用 - " + e.getMessage(),
                        utf8SessionId, true);
                errorEmitter.send(SseEmitter.event()
                        .name("error")
                        .data(errorResponse));
                errorEmitter.complete();
            } catch (Exception ex) {
                errorEmitter.completeWithError(ex);
            }

            return ResponseEntity.status(500)
                    .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_EVENT_STREAM_VALUE + ";charset=UTF-8")
                    .body(errorEmitter);
        }
    }

    /**
     * 普通聊天接口（非流式）- 优化字符编码
     */
    @PostMapping(value = "/message", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public ResponseEntity<Map<String, Object>> chat(@RequestBody ChatRequest request) {
        log.info("收到非流式聊天请求，消息长度: {} 字符",
                request.getMessage() != null ? request.getMessage().length() : 0);

        // 参数验证
        if (request.getMessage() == null || request.getMessage().trim().isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "消息不能为空");
            errorResponse.put("timestamp", System.currentTimeMillis());

            return ResponseEntity.badRequest()
                    .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
                    .body(errorResponse);
        }

        if (request.getMessage().length() > 4000) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "消息长度不能超过4000字符");
            errorResponse.put("timestamp", System.currentTimeMillis());

            return ResponseEntity.badRequest()
                    .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
                    .body(errorResponse);
        }

        try {
            String sessionId = request.getSessionId();
            if (sessionId == null || sessionId.trim().isEmpty()) {
                sessionId = UUID.randomUUID().toString();
            }

            // 确保输入是UTF-8编码
            String utf8Message = ensureUtf8(request.getMessage().trim());
            String utf8SessionId = ensureUtf8(sessionId);

            ChatResponse response = sparkAiService.chat(utf8Message, utf8SessionId);

            // 确保响应也是UTF-8编码
            String utf8Content = ensureUtf8(response.getMessage());
            response.setMessage(utf8Content);

            Map<String, Object> jsonResponse = new HashMap<>();
            jsonResponse.put("success", true);
            jsonResponse.put("data", response);
            jsonResponse.put("timestamp", System.currentTimeMillis());

            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
                    .body(jsonResponse);

        } catch (Exception e) {
            log.error("非流式聊天失败: {}", e.getMessage());

            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "AI服务暂时不可用: " + e.getMessage());
            errorResponse.put("timestamp", System.currentTimeMillis());

            return ResponseEntity.status(500)
                    .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
                    .body(errorResponse);
        }
    }

    /**
     * 获取会话历史 - 优化字符编码
     */
    @GetMapping(value = "/history/{sessionId}", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public ResponseEntity<Map<String, Object>> getHistory(@PathVariable String sessionId) {
        log.info("获取会话历史: {}", sessionId);

        try {
            String utf8SessionId = ensureUtf8(sessionId);
            List<RoleContent> history = sparkAiService.getSessionHistory(utf8SessionId);

            // 确保历史记录中的内容都是UTF-8编码
            history.forEach(roleContent -> {
                String utf8Content = ensureUtf8(roleContent.getContent());
                roleContent.setContent(utf8Content);
            });

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("sessionId", utf8SessionId);
            response.put("history", history);
            response.put("count", history.size());
            response.put("timestamp", System.currentTimeMillis());

            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
                    .body(response);

        } catch (Exception e) {
            log.error("获取会话历史失败: {}", e.getMessage());

            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "获取会话历史失败: " + e.getMessage());
            errorResponse.put("timestamp", System.currentTimeMillis());

            return ResponseEntity.status(500)
                    .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
                    .body(errorResponse);
        }
    }

    /**
     * 清除会话历史 - 优化字符编码
     */
    @DeleteMapping(value = "/history/{sessionId}", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public ResponseEntity<Map<String, Object>> clearHistory(@PathVariable String sessionId) {
        log.info("清除会话历史: {}", sessionId);

        try {
            String utf8SessionId = ensureUtf8(sessionId);
            sparkAiService.clearSession(utf8SessionId);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "会话历史已清除");
            response.put("sessionId", utf8SessionId);
            response.put("timestamp", System.currentTimeMillis());

            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
                    .body(response);

        } catch (Exception e) {
            log.error("清除会话历史失败: {}", e.getMessage());

            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "清除会话历史失败: " + e.getMessage());
            errorResponse.put("timestamp", System.currentTimeMillis());

            return ResponseEntity.status(500)
                    .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
                    .body(errorResponse);
        }
    }

    /**
     * 创建新会话 - 优化字符编码
     */
    @PostMapping(value = "/session/new", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public ResponseEntity<Map<String, Object>> createSession() {
        String sessionId = UUID.randomUUID().toString();
        log.info("创建新会话: {}", sessionId);

        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("sessionId", sessionId);
        response.put("message", "新会话已创建");
        response.put("timestamp", System.currentTimeMillis());

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
                .body(response);
    }

    /**
     * 健康检查接口 - 优化字符编码
     */
    @GetMapping(value = "/health", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public ResponseEntity<Map<String, Object>> health() {
        Map<String, Object> response = new HashMap<>();
        response.put("status", "healthy");
        response.put("service", "Spark AI Service");
        response.put("timestamp", System.currentTimeMillis());
        response.put("version", "2.1.0");
        response.put("encoding", "UTF-8");

        Map<String, String> endpoints = new HashMap<>();
        endpoints.put("stream", "POST /stream {\"message\":\"你好\",\"sessionId\":\"xxx\"}");
        endpoints.put("message", "POST /message {\"message\":\"你好\",\"sessionId\":\"xxx\"}");
        endpoints.put("history", "GET /history/{sessionId}");
        endpoints.put("clear", "DELETE /history/{sessionId}");
        endpoints.put("newSession", "POST /session/new");
        response.put("endpoints", endpoints);

        Map<String, String> features = new HashMap<>();
        features.put("streaming", "支持实时流式聊天");
        features.put("sessionManagement", "会话历史管理");
        features.put("errorHandling", "完善的错误处理");
        features.put("encoding", "UTF-8字符编码支持");
        features.put("webSocket", "基于WebSocket的实时通信");
        response.put("features", features);

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
                .body(response);
    }

    /**
     * 获取服务信息
     */
    @GetMapping(value = "/info", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public ResponseEntity<Map<String, Object>> getServiceInfo() {
        Map<String, Object> response = new HashMap<>();
        response.put("provider", "讯飞星火");
        response.put("model", "4.0Ultra");
        response.put("capabilities", new String[]{"chat", "stream", "chinese", "english", "medical"});
        response.put("maxTokens", 4096);
        response.put("temperature", 0.5);
        response.put("supportedFormats", new String[]{"text/event-stream", "application/json"});
        response.put("encoding", "UTF-8");
        response.put("timeout", "30秒");

        Map<String, String> specialFeatures = new HashMap<>();
        specialFeatures.put("medicalExpert", "专业医生角色设定");
        specialFeatures.put("contextManagement", "智能上下文管理");
        specialFeatures.put("streamingOptimized", "优化的流式传输");
        specialFeatures.put("encodingFixed", "修复字符编码问题");
        response.put("specialFeatures", specialFeatures);

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
                .body(response);
    }

    /**
     * 确保字符串是UTF-8编码的辅助方法 - 参考DeepSeek的实现
     */
    private String ensureUtf8(String input) {
        if (input == null) {
            return "";
        }

        try {
            // 检测并转换字符编码
            byte[] bytes = input.getBytes(StandardCharsets.UTF_8);
            String reconstructed = new String(bytes, StandardCharsets.UTF_8);

            // 如果重构后的字符串与原字符串相同，说明编码正确
            if (reconstructed.equals(input)) {
                return input;
            }

            // 尝试从ISO-8859-1转换为UTF-8（常见的乱码情况）
            byte[] isoBytes = input.getBytes(StandardCharsets.ISO_8859_1);
            String utf8String = new String(isoBytes, StandardCharsets.UTF_8);

            log.debug("字符编码转换: '{}' -> '{}'", input, utf8String);
            return utf8String;

        } catch (Exception e) {
            log.warn("字符编码转换失败，返回原始字符串: {}", e.getMessage());
            return input;
        }
    }
}
